package org.kumas.sgrpc.rpc.protocol;

import java.util.List;

import org.kumas.sgrpc.common.URL;
import org.kumas.sgrpc.common.constants.CommonConstants;
import org.kumas.sgrpc.common.extension.Activate;
import org.kumas.sgrpc.common.extension.ExtensionLoader;
import org.kumas.sgrpc.remoting.utils.UrlUtils;
import org.kumas.sgrpc.rpc.Exporter;
import org.kumas.sgrpc.rpc.Filter;
import org.kumas.sgrpc.rpc.Invoker;
import org.kumas.sgrpc.rpc.Protocol;
import org.kumas.sgrpc.rpc.ProtocolServer;
import org.kumas.sgrpc.rpc.RpcException;

import static org.kumas.sgrpc.common.constants.CommonConstants.SERVICE_FILTER_KEY;

@Activate(order = 100)
public class ProtocolFilterWrapper implements Protocol {

    private final Protocol protocol;

    public ProtocolFilterWrapper(Protocol protocol) {
        if (protocol == null) {
            throw new IllegalArgumentException("protocol == null");
        }
        this.protocol = protocol;
    }

    private static <T> Invoker<T> buildInvokerChain(final Invoker<T> invoker, String key, String group) {
        Invoker<T> last = invoker;
        List<Filter> filters = ExtensionLoader
            .getExtensionLoader(Filter.class).getActivateExtension(invoker.getUrl(), key, group);

        if (!filters.isEmpty()) {
            for (int i = filters.size() - 1; i >= 0; i--) {
                final Filter filter = filters.get(i);
                last = new FilterNode<T>(invoker, last, filter);
            }
        }

        return last;
    }

    @Override
    public int getDefaultPort() {
        return protocol.getDefaultPort();
    }

    @Override
    public <T> Exporter<T> export(Invoker<T> invoker) throws RpcException {
        if (UrlUtils.isRegistry(invoker.getUrl())) {
            return protocol.export(invoker);
        }
        return protocol.export(buildInvokerChain(invoker, SERVICE_FILTER_KEY, CommonConstants.PROVIDER));
    }

    @Override
    public <T> Invoker<T> refer(Class<T> type, URL url) throws RpcException {
        if (UrlUtils.isRegistry(url)) {
            return protocol.refer(type, url);
        }
        return buildInvokerChain(protocol.refer(type, url), CommonConstants.REFERENCE_FILTER_KEY, CommonConstants.CONSUMER);
    }

    @Override
    public void destroy() {
        protocol.destroy();
    }

    @Override
    public List<ProtocolServer> getServers() {
        return protocol.getServers();
    }

}